import 'dart:ui';

import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/alert_business/video/share_video_dialog.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/extension/date_string_extension.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/darkweb/widget/shrink_wrap.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import 'album_action_widget.dart';
import 'pics_detail_logic.dart';

//图集详情页
class PicsDetailPage extends StatelessWidget {
  final String? id;

  PicsDetailPage({Key? key, this.id}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: PicsDetailLogic(id),
      tag: "$id${DateTime.now().millisecondsSinceEpoch}",
      builder: (logic) {
        return Scaffold(
          appBar: AppBar(
            title: Text('${logic.videoModel?.title ?? ''}'),
            actions: [
              InkWell(
                onTap: () {
                  Get.dialog(
                    ShareVideoDialog(
                      isCoverV: true,
                      videoModel: VideoModel()
                        ..id = logic.videoModel?.id
                        ..cover = logic.videoModel?.cover,
                    ),
                  );
                },
                child: Image.asset("acg_share.png".acgImgPath, width: 24),
              ).paddingOnly(right: 16)
            ],
          ),
          body: SafeArea(child: () {
            if (logic.videoModel == null) return LoadingCenterWidget();
            if (logic.videoModel?.id == null)
              return CErrorWidget(
                retryOnTap: () => logic.loadData(),
              );
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                    child: Stack(
                  children: [
                    () {
                      //画廊模式
                      if (logic.galleryMode.value) {
                        return GridView.builder(
                          itemCount: logic.videoModel?.seriesCover?.length ?? 0,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            childAspectRatio: 168 / 224,
                            mainAxisSpacing: 8,
                            crossAxisSpacing: 7,
                          ),
                          itemBuilder: (context, index) {
                            return _buildItem(logic, index);
                          },
                        );
                      } else {
                        return ListView.separated(
                          padding: EdgeInsets.symmetric(horizontal: 16),
                          itemCount: logic.videoModel?.seriesCover?.length ?? 0,
                          separatorBuilder: (context, index) => 8.sizeBoxH,
                          itemBuilder: (context, index) {
                            return _buildItem(logic, index);
                          },
                        );
                      }
                    }(),
                    Positioned(
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: _buildHeaderInfo(logic),
                    ),
                  ],
                )),
                Obx(
                  () => AlbumActionWidget(
                    videoModel: logic.videoModel,
                    currentIndex: -1,
                    galleryMode: logic.galleryMode.value,
                    tapAction: (p0) => logic.changeGalleryMode(),
                  ),
                ),
              ],
            );
          }()),
        );
      },
    );
  }

  _buildItem(PicsDetailLogic logic, int index) {
    String? imageUrl = logic.videoModel?.seriesCover?[index];
    //0-不需要解锁 1-金币解锁 2-会员解锁
    bool showLock = logic.videoModel?.picLockType != 0 && index > 1;
    return InkWell(
      onTap: () => logic.onImgItemClick(index),
      child: Stack(
        children: [
          Container(
            width: logic.galleryMode.value ? double.infinity : null,
            height: logic.galleryMode.value ? double.infinity : null,
            child: showLock
                ? ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: ImageFiltered(
                      imageFilter: ImageFilter.blur(sigmaX: 8, sigmaY: 8),
                      child: NetworkImageLoader(
                        imageUrl: imageUrl,
                        compress: true,
                        borderRadius: 12,
                      ),
                    ),
                  )
                : NetworkImageLoader(
                    imageUrl: imageUrl,
                    compress: true,
                    borderRadius: 12,
                  ),
          ),
          if (showLock) ...[
            Positioned.fill(
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(color: Colors.black.withOpacity(.5)),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset('pic_lock.webp'.communityPath, width: 48),
                    12.sizeBoxH,
                    EasyRichText(
                      logic.videoModel?.picLockType == 1 ? '${logic.videoModel?.coins ?? 0}金币解锁看完整图集' : '开通会员看完整图集',
                      defaultStyle: textStyle(12, Colors.white, FontWeight.w400),
                      patternList: [
                        EasyRichTextPattern(
                          targetString: '${logic.videoModel?.coins ?? 0}金币',
                          style: TextStyle(color: Color(0xffFD2D55)),
                        ),
                        EasyRichTextPattern(
                          targetString: '开通会员',
                          style: TextStyle(color: Color(0xffFD2D55)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ]
        ],
      ),
    );
  }

  _buildHeaderInfo(PicsDetailLogic _) {
    return Container(
      margin: EdgeInsets.fromLTRB(36, 136, 36, 12),
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20),
        color: Color(0xff22242E),
      ),
      child: Row(
        children: [
          NetworkImageLoader(
            imageUrl: _.videoModel?.publisher?.portrait ?? '',
            width: 60,
            height: 60,
            borderRadius: 30,
          ),
          14.sizeBoxW,
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    '${_.videoModel?.publisher?.name ?? ''}',
                    style: textStyle(14, Colors.white, FontWeight.w500),
                  ),
                  8.sizeBoxW,
                  Container(
                    decoration: BoxDecoration(
                      color: Color(0xffFD2D55).withOpacity(.2),
                      borderRadius: BorderRadius.circular(3),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                    child: Text(
                      '共计${_.videoModel?.seriesCover?.length ?? 0}张',
                      style: textStyle(12, Color(0xffFD2D55), FontWeight.w500),
                    ),
                  )
                ],
              ),
              4.sizeBoxH,
              Text(
                '${_.videoModel?.reviewAt?.utcTimeSToYMDString(gap: '-')} ｜ ${_.videoModel?.pageViewCount.humanizeFormat}观看',
                style: textStyle(12, Color(0xff656565), FontWeight.w500),
              ),
              if (_.videoModel?.tags?.isNotEmpty == true) ...[
                4.sizeBoxH,
                ShrinkWrap(
                    spacing: 0,
                    runSpacing: 6,
                    maxLines: 1,
                    children: _.videoModel!.tags!
                        .map(
                          (e) => Text(
                            '#${e.name ?? ''}',
                            style: TextStyle(
                              fontSize: 11,
                              color: Color(0xffEFB203),
                            ),
                          ),
                        )
                        .toList())
              ]
            ],
          ))
        ],
      ),
    );
  }
}
